package com.macaline.concurrent.demo;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Share {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();


    public void add() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) {
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "：" + number);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public void sub() throws InterruptedException {
        lock.lock();
        try {
            while (number != 1) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "：" + number);
            condition.signalAll();
        }finally{
            lock.unlock();
        }
    }
//
//    public synchronized void add() throws InterruptedException {
//        while (number != 0) {
//            this.wait();
//        }
//        number++;
//        System.out.println(Thread.currentThread().getName() + "：" + number);
//        this.notifyAll();
//    }
//
//    public synchronized void sub() throws InterruptedException {
//        while (number != 1) {
//            this.wait();
//        }
//        number--;
//        System.out.println(Thread.currentThread().getName() + "：" + number);
//        this.notifyAll();
//    }



}

public class SAddOne {

    public static void main(String[] args) {
        Share share = new Share();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.sub();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "CC").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.sub();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "DD").start();

    }
}
